package main

import (
	"flag"
	"fmt"
	"net"

	slib "gitee.com/xiaoa7/socklib"
)

var (
	addr = flag.String("addr", ":8080", "服务监听地址")
)

func init() {
	flag.Parse()
}

func main() {
	listener, err := net.Listen("tcp", *addr)
	if err != nil {
		fmt.Printf("服务监听失败: %v\n", err)
		return
	}
	fmt.Println("服务监听地址:", *addr)
	for {
		// 等待连接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("接受连接出错: %v\n", err)
			continue
		}
		//
		go handler(conn)
	}
}

//
func handler(conn net.Conn) {
	//
	greetFrame := slib.DefaultDataFrameFactory.BuildFrame([]byte(fmt.Sprintf("Hello %s!", conn.RemoteAddr().String())))
	conn.Write(greetFrame)
	//
	for {
		bs, err := slib.DefaultDataFrameFactory.ReadFrame(conn)
		if err != nil {
			break
		} else {
			fmt.Printf("on %s read :: % X %s \n",
				conn.RemoteAddr().String(),
				bs,
				string(bs))
		}
		//重新封包
		resp := slib.DefaultDataFrameFactory.BuildFrame(bs)
		conn.Write(resp)
	}
}
